import React from 'react'
import { Card, Row, Col } from 'antd'
import { useSelector } from 'react-redux'
import { indexApi } from '../apis'
import '../assets/styles/home.less'
import * as echarts from 'echarts'
export default function Home() {
  const avatar = useSelector(state => {
    return state.avatar.avatar
  })
  const user = JSON.parse(localStorage.user)
  const [ipData, setIpData] = React.useState({})
  //获取最近七天的日期
  function getRecentlySevenDays() {
    const now = Date.now();//现在时刻的时间戳
    const dayMillionseconds = 24 * 60 * 60 * 1000;//每天的毫秒数
    const res = [];//最近七天的日期
    for (let i = 0; i < 7; i++) {
      const d = new Date(now - dayMillionseconds * i);
      const mon = d.getMonth() + 1;//获取月份
      const date = d.getDate();//获取号数
      res.unshift(`${mon}-${date}`);
    }

    return res;
  }
  React.useEffect(() => {
    indexApi(user.username).then(res => {
      console.log(res);
      setIpData(res.data)
      const lastSevenVisitCount = res.data.lastSevenVisitCount
      const yData = []
      lastSevenVisitCount.forEach(item => {
        yData.push(item.count)
      })
      let len = yData.length
      while (len < 7) {
        yData.unshift(0)
        len = yData.length
      }
      var myChart = echarts.init(document.getElementById('myEcharts'));
      const xData = getRecentlySevenDays()
      myChart.setOption({
        title: {
          text: '七天访问记录'
        },
        tooltip: {},
        xAxis: {
          data: xData
        },
        yAxis: {},
        series: [
          {
            name: '访问量',
            type: 'bar',
            data: yData
          }
        ]
      });
    })

  }, [])

  return (
    <div>
      <Card style={{ width: '100%',marginBottom:'10px' }} bodyStyle={{ display: 'flex', justifyContent: 'space-between' }}>
        <div className='left'>
          <img src={"http://xawn.f3322.net:8002/distremote/static/avatar/" + avatar} alt="" />
          <div>
            <p>{user.username}</p>
            <p>{user.deptName || '暂无部门'} | {user.roleName || '暂无职务'}</p>
            <p>上次登陆时间：{user.lastLoginTime}</p>
          </div>

        </div>
        <div className='right'>
          <div>
            <h1>今日IP</h1>
            <p>{ipData.todayIp}</p>
          </div>
          <div>
            <h1>今日访问</h1>
            <p>{ipData.todayVisitCount}</p>
          </div>
          <div>
            <h1>总访问量</h1>
            <p>{ipData.totalVisitCount}</p>
          </div>
        </div>
      </Card>
      <Row gutter={8}>
        <Col span={12}>
          <Card style={{ width: '100%', }}>
            <div style={{ width: 750, height: 300 }} id='myEcharts'>

            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card style={{width:'100%'}} title='进行中的项目' extra={<a href="#" style={{ color: '#1890ff' }}>所有项目</a>}>
            暂无
          </Card>
        </Col>
      </Row>
    </div>
  )
}
